package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.ITravelService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Redis 缓存数据初始化监听器
 *
 * mongodb --> redis
 *
 * 1> 攻略统计对象vo
 * 2> 用户攻略收藏列表
 */
@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ITravelService travelService;
    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    // 当spring容器启动并初始化之后马上执行该方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        System.out.println("------攻略vo对象初始化 start------");

        // 查询所有攻略
        List<Strategy> list = strategyService.list();
        // 遍历所有攻略 封装成vo对象
        for (Strategy strategy : list) {

            // 如果vo已经存在 则跳过
            if (strategyStatisVORedisService.isStrategyExist(strategy.getId())) continue;

            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
            // 将vo 缓存到redis
            strategyStatisVORedisService.setStrategyStatisVo(vo);
        }
        System.out.println("------攻略vo对象初始化 end------");

        System.out.println("------游记vo对象初始化 start------");

        // 查询所有游记
        List<Travel> travels = travelService.list();
        // 遍历所有游记 封装成vo对象
        for (Travel travel : travels) {
            // 如果vo已经存在 则跳过
            if (strategyStatisVORedisService.isStrategyExist(travel.getId())) continue;

            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(travel, vo);
            vo.setTravelId(travel.getId());
            // 将vo 缓存到redis
            strategyStatisVORedisService.setTravelStatisVo(vo);
        }
        System.out.println("------游记vo对象初始化 end------");
    }
}
